package com.lx.java8;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

import org.junit.Test;

public class ParallelStreamDriver {

	Long max = 100000000000L;

	/**
	 * 串行，就是直接使用for循环：耗时53671
	 */
	@Test
	public void serial() {
		long sum = 0;
		long start = System.currentTimeMillis();
		for (long i = 0; i < max; i++) {
			sum += i;
		}
		long end = System.currentTimeMillis();
		System.out.println("总共耗时为：" + (end - start));
	}

	/**
	 * Java7并行计算：耗时：35858
	 * 比串行快，但是写代码比较复杂，需要写一个辅助的拆分类
	 */
	@Test
	public void java7parallel() {
		ForkJoinPool pool = new ForkJoinPool();
		ForkJoinTask<Long> t = new ForkCalculater(0, max);
		long sum = 0;
		long start = System.currentTimeMillis();
		Long invoke = pool.invoke(t);
		long end = System.currentTimeMillis();
		System.out.println("总共耗时为：" + (end - start));
	}
	
	
	/**
	 * Java8并行流，代码非常简单，耗时：35357
	 */
	@Test
	public void java8Parallel(){
		long start = System.currentTimeMillis();
		long sum = LongStream.range(0, max)
			.parallel() //获取并行流
			.sum();
		long end = System.currentTimeMillis();
		System.out.println("总共耗时为：" + (end - start));
	}

	@Test
	public void useParallelStreams() {
		// 初始化一个字符串集合
		List<String> values = new ArrayList<>();

		for (int i = 0; i < max; i++) {
			UUID uuid = UUID.randomUUID();
			values.add(uuid.toString());
		}

		// 使用顺序流排序
		long sequenceT0 = System.nanoTime();
		values.stream().sorted();
		long sequenceT1 = System.nanoTime();

		// 输出:sequential sort took: 51921 ms.
		System.out.format("sequential sort took: %d ms.", sequenceT1 - sequenceT0).println();

		// 使用并行流排序
		long parallelT0 = System.nanoTime();
		// default Stream<E> parallelStream() {
		// parallelStream为Collection接口的一个默认方法
		values.parallelStream().sorted();
		long parallelT1 = System.nanoTime();

		// 输出:parallel sort took: 21432 ms.
		System.out.format("parallel sort took: %d ms.", parallelT1 - parallelT0).println();
		// 从输出可以看出：并行排序快了一倍多
	}


}
